package com.yao.controller;

import com.yao.context.BaseContext;
import com.yao.exception.custom.PathExcption;
import com.yao.mapper.ArticleMapper;
import com.yao.mapper.UserMapper;
import com.yao.pojo.Article;
import com.yao.pojo.Result;
import com.yao.pojo.User;
import com.yao.utils.AliOSSUtils;
import com.yao.utils.PathCorrect;
import com.yao.utils.PathDetermine;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;

@Slf4j
@RestController
@Api(tags = "AliyunOSS -> 文件相关操作")
public class UploadController {

    private AliOSSUtils aliOSSUtils;
    private UserMapper userMapper;
    private ArticleMapper articleMapper;

    @Autowired
    public void UploadController(UserMapper userMapper, AliOSSUtils aliOSSUtils, ArticleMapper articleMapper){
        this.userMapper = userMapper;
        this.aliOSSUtils = aliOSSUtils;
        this.articleMapper = articleMapper;
    }

    /**
     * 上传用户头像
     * @param multipartFile
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/user/upload")
    @ApiOperation("上传用户头像")
    public Result uploadUserAvatar(MultipartFile multipartFile){
        String fileName = multipartFile.getOriginalFilename();
        log.info("图片上传...{}",fileName);

        User userParam = User.builder()
                .id(BaseContext.getCurrentId())
                .build();
        String oldUrl = userMapper.findEqualUser(userParam).getUserPic();

        try {
            try {
                PathDetermine.picPath(fileName);
            } catch (PathExcption pathExcption) {
                log.info("路径异常...{},路径为...{}",pathExcption.getMessage(),fileName);
                return Result.error("PATH_EXCPTION");
            }

            String url = aliOSSUtils.upload(multipartFile);

            userParam.setUserPic(url);
            userParam.setUpdateTime(LocalDateTime.now());
            userMapper.changeUserInfo(userParam);
            log.info("旧图片地址...{}",oldUrl);

            // 删除aliyun上的旧图片
            if ((StringUtils.hasLength(oldUrl))) aliOSSUtils.deleteFile(PathCorrect.correct(oldUrl));
            return Result.success(url);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("文件上传失败");
        }
    }

    /**
     * 上传文章图片
     * @param multipartFile
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/article/upload/{id}")
    @ApiOperation("上传文章图片")
    public Result uploadArticlePic(MultipartFile multipartFile, @PathVariable Integer id){
        String fileName = multipartFile.getOriginalFilename();
        log.info("图片上传...{}",fileName);

        Article newArticle = Article.builder()
                .id(id)
                .build();
        Article article = articleMapper.findEqualArticle(id);
        String oldUrl = article.getCoverImg();

        Integer createUser = article.getCreateUser();
        Integer currentId = BaseContext.getCurrentId();
        if (createUser != currentId){
            log.info("当前用户ID...{},操作用户ID...{}的文章",currentId,createUser);
            return Result.success("暂无权限");
        }


        try {
            try {
                PathDetermine.picPath(fileName);
            } catch (PathExcption pathExcption) {
                log.info("路径异常...{},路径为...{}",pathExcption.getMessage(),fileName);
                return Result.error("PATH_EXCPTION");
            }

            // 上传到云端返回url
            String url = aliOSSUtils.upload(multipartFile);

            newArticle.setCoverImg(url);
            newArticle.setUpdateTime(LocalDateTime.now());
            articleMapper.changeArticle(newArticle);
            log.info("旧图片地址...{}",oldUrl);

            // 删除aliyun上的旧图片
            if ((StringUtils.hasLength(oldUrl))) aliOSSUtils.deleteFile(PathCorrect.correct(oldUrl));
            return Result.success(url);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("文件上传失败");
        }
    }

}
